#include <QDebug>
#include "SearchResult.h"

SearchResult::SearchResult(QWidget *parent) :
    QTreeWidget(parent)
{
    setColumnCount(1);
    setHeaderHidden(true);
    setItemsExpandable(true);
    connect(this, SIGNAL(itemDoubleClicked(QTreeWidgetItem*,int)), SLOT(itemdClicked(QTreeWidgetItem*,int)));
}

SearchResult::~SearchResult()
{

}

void SearchResult::setResult(const QStringList& list)
{
    clear();
    QMap<QString, QTreeWidgetItem *> items;
    foreach(QString it, list){
        QStringList ch = it.split(":");
        if (ch.length() != 3)
            continue;
        if (!items.contains(ch[0])){
            items[ch[0]] = new QTreeWidgetItem((QTreeWidget*)0, QStringList() << ch[0] + " (" + QString::number(list.filter(ch[0]).length()) + ")");
            items[ch[0]]->setChildIndicatorPolicy(QTreeWidgetItem::DontShowIndicatorWhenChildless);
        }
        QTreeWidgetItem *tit = new QTreeWidgetItem((QTreeWidget*)0, QStringList() << "Line " + ch[1] + ": " + ch[2].trimmed());
        tit->setData(0, Qt::UserRole, ch[0]);
        tit->setData(0, Qt::UserRole+1, ch[1]);
        items[ch[0]]->addChild(tit);
    }
    addTopLevelItems(items.values());
    collapseAll();
}

void SearchResult::itemdClicked(QTreeWidgetItem* item, int /*col*/)
{
    if (!item->data(0, Qt::UserRole).isNull()){
        emit jumpFile(item->data(0, Qt::UserRole).toString(), item->data(0, Qt::UserRole+1).toInt());
    }
}
